#!/bin/python

##########################################################
# PROJECT : GPRS Server
# FILE    : socketServer.py
# USAGE	  : receive cmd from server,record in list 'msg'
# CREATION: 20101011
# LICENSE : ISCAS
# $Id$      Qi Chen
##########################################################
import signal, os
import socket
import time
import threading
import traceback
import binascii
'''
global virable 
'''
HOST = ''        # Symbolic name meaning the local host
PORT = 8001      # Arbitrary non-privileged port
exitFlag=False
msg=[]
socketlist=[]
'''
set Ctrl-C handler
@param :connection,address
@return :
'''
def handler(signum, frame):
    exitFlag=True
    print 'Signal handler called with Ctrl-C' 
    os._exit(1)

'''
start a thread to receive the cmd from server,and record in file
@param :connection,address
@return :
'''	
class ReceiveThread(threading.Thread):
    def __init__(self, conn):
        threading.Thread.__init__(self)
        self.sock = conn
         
    def run(self,):
    	global msg, exitFlag, socketlist
    	while not exitFlag:
            try:
            	self.buffer = self.sock.recv(1024)
            	if self.buffer != '':
                    msg.append(self.buffer)
                #self.conn.close()
            except Exception, error:
               	 print '[!!Error in socketServer:] GW receive faild:', error
                 socketlist.remove(self.sock)
               	 raise 
        self.stop()

    def stop(self,):
        self.sock.close()

def send(pkt):    
    global msg, exitFlag, socketlist
    Flag = False
    if len(socketlist) == 0:
        return Flag
    for s in socketlist:
        try:
            s.send(pkt)
            Flag = True
        except socket.error, error:
            print '[!!Error in socketServer:] GW send faild:', error
            socketlist.remove(s)
    return Flag

class server(threading.Thread):
    def __init__(self,):
        threading.Thread.__init__(self)
        global exitFlag, HOST, PORT
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.data=''
        try:
            self.s.bind((HOST, PORT))
            print "[Info in socketServer:]The server running at :",PORT
            self.start()
        except socket.error,msg:
            print "[!!Error in socketServer:]the port %d is already in use"%PORT
            self.s.close()
            os._exit(1)
            raise

    def run(self,):
        global exitFlag, SERVERHOST, SERVERPORT, msg, socketlist
        self.s.listen(5)       
        while not exitFlag:
            try:
                conn, addr = self.s.accept()
                print 'connected from', addr
                socketlist.append(conn)
                rsocket = ReceiveThread(conn)
                rsocket.start()
            except Exception, error:
                print '[!!Error in socketServer:]Starting socketThread failed:',error
                raise
    def stop(self,):
        print '$$$socket closing!!!'
        self.s.close()
        
'''
provide the API receive() outside
return the list msg's first cmd
@param:none
@return : string msg or ''
'''
def receive():
    global msg
    if len(msg):
        temp=msg[0]
	delete()
	return temp
    else:
	return ''
    
'''
delete the cmd after receive()
'''
def delete():
    global msg
    if len(msg):
        del msg[0]
        
'''
in case of exception,for recovering the cmd list
'''
def insert(cmd):
    global msg
    msg.insert(0,cmd)
		
if __name__=='__main__':
    signal.signal(signal.SIGINT,handler)
    s=server()
    send("testing")
    

